import { wait } from '@/utils/util'
import { defineStore } from 'pinia'
import { ref } from 'vue'

// loading状态管理
const requestTotal = ref(0)

// 是否允许添加loading
let loadingLock = false

let loadingTotal = 0

const downloadFileName = ref('')

/**
 * 全局loading管理
 */
async function updateRequestLoading(num: number) {
    loadingTotal += num
    if (num > 0 && requestTotal.value === 0) {
        await wait(1000)
    }
    if (num > 0 && loadingLock) return
    requestTotal.value = loadingTotal
}

/**
 * 全局loading清除
 */
async function clearRequestLoading() {
    requestTotal.value = 0
    loadingTotal = 0

    // 一秒内禁止新增loading
    loadingLock = true
    await wait(1000)
    loadingLock = false
}

/**
 * 设置导出流文件时的文件名
 * @param name 
 */
function setDownLoadFileName(name: string) {
    downloadFileName.value = name
}

export default defineStore('config', () => {
    return {
        requestTotal,
        updateRequestLoading,
        clearRequestLoading,
        downloadFileName,
        setDownLoadFileName
    }
})
